package exttable.formgenerator;

import dbutils.DbUtils;

import javax.swing.*;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by IntelliJ IDEA.
 * User: ADMIN
 * Date: 05.08.2010
 * Time: 12:10:48
 * To change this template use File | Settings | File Templates.
 */
public class ViewDataBaseTableModel {
    static JFrame frame;
    String tableName;
    String query;

    ViewDataBaseTableModel(String tableName) throws Exception {
        PreparedStatement ps;
         Connection conn = DbUtils.getDBConnectionGeneral();
        frame = new JFrame(TranslateFields.getTranslateOfColumnOrOfTable("table_traslation_list", "table_name", tableName, conn));
        frame.setName("Form to insert");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {

            ps = conn.prepareStatement("");
            if(tableName.equals("units")){
                query="select combination_key,numerator,denominator from " + tableName + "";

            }
            else{
                query="select name_ru,name_en,name_kk from " + tableName + "";
            }
            ResultSet rs = ps.executeQuery(query);
            DatabaseTableModel dbm = new DatabaseTableModel(false);
            dbm.setDataSource(rs, tableName, conn);
            // таблица и окно
            JTable table = new JTable(dbm);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            setColumnSize(table,8);
            frame.add(new JScrollPane(table), BorderLayout.NORTH);
            conn.close();
        } catch (Exception excep) {
            excep.printStackTrace();
        }
        frame.add(FormGenerator.generatePanel(tableName));
        frame.setSize(600, 570);
        frame.setVisible(true);
    }

    public static void setColumnSize(JTable table, int multiplier ) {
        /*
        This method set column size for JTable, it checks names of columns and data in rows.
        Then it return the largest string length  multiplayed on multiplier
         */
        for (int i = 0; i < table.getColumnCount(); i++) {
            int width = 0;
            String columnNameStr = table.getColumnName(i);
            if (columnNameStr.length() > width) {
                width = columnNameStr.length();
            }
            TableColumn column = table.getColumnModel().getColumn(i);
            int rowCount = table.getRowCount();
            String str = "";
            for (int k = 0; k < rowCount; k++) {
                str = table.getModel().getValueAt(k, i).toString();
                //System.out.println("column "+table.getColumnName(i)+ "  value = "+ str);
                if (str.length() > width) {
                    width = str.length();
                }

            }
            column.setMinWidth(width * multiplier);
        }
    }


}
